#!/usr/bin/python
# -*- coding: utf-8 -*-

#######################################
#                                     #
# script.module.t0mus.common for xbmc #
# author: t0mus                       #
#                                     #
#######################################

"""Url extractor for megustavid host."""

import re
from t0mus.common.common import open_url
from BeautifulSoup import BeautifulSoup


def scan_for_player(url):
    """Scans url looking for player."""

    html = open_url(url).read()
    soup = BeautifulSoup(html)
    playlist_id = soup.find('object',
            attrs={'id': 'nuevoplayer'}).find('param',
            attrs={'name': 'flashvars'})['value'].split('=')[2]
    return playlist_id


def extract_urls(soup):
    """Return list of urls."""

    urls = []
    try:
        pattern = '^http://www.megustavid.com/'
        pattern2 = '^http://(www.)*megustavid.com/e='
        for frame in soup.findAll('iframe',
                                  attrs={'src': re.compile(pattern)}):
            playlist_id = scan_for_player(frame['src'])

            urls.append(parse_playlist(playlist_id))
        for anchor in soup.findAll('a',
                                  attrs={'href': re.compile(pattern2)}):
            playlist_id = scan_for_player(anchor['href'])
            urls.append(parse_playlist(playlist_id))
    except AttributeError:
        pass
    return urls


def parse_playlist(playlist_id):
    """ Searches for id in playlist."""

    result = None
    html = \
        open_url('http://megustavid.com/media/nuevo/player/playlist.php?id='
                 + str(playlist_id)).read()
    soup = BeautifulSoup(html)
    result = soup.find('file').string
    return result


